package rpc

import (
	"context"
	"errors"

	"bmember/internal/object"

	"bmember/internal/service"
	"bmember/pkg/lueerror"

	"google.golang.org/grpc"

	pb "bmember/api/pb/server"
)

type aRpcHandler struct {
	*RpcBase
	pb.UnimplementedAssetServer
	name string
}

// NewAssetRpcHandler 会员资产相关
func NewAssetRpcHandler() *aRpcHandler {
	return &aRpcHandler{
		RpcBase:                  base,
		UnimplementedAssetServer: pb.UnimplementedAssetServer{},
		name:                     "rpc_asset_handler",
	}
}

// RegisterHandler 服务注册
func (hl *aRpcHandler) RegisterHandler(server *grpc.Server) {
	pb.RegisterAssetServer(server, hl)
}

// MemberBalancePay 会员余额支付
func (hl *aRpcHandler) MemberBalancePay(ctx context.Context, req *pb.MemberBalancePayReq) (*pb.BalanceInfoReply, error) {
	if req == nil {
		return nil, nil
	}
	cardInfo := &object.CardInfo{}
	err := json.Unmarshal(req.CardInfo, cardInfo)
	if err != nil {
		return nil, lueerror.InvalidRequest(err)
	}
	if cardInfo.AccId == 0 {
		return nil, lueerror.InvalidRequest(errors.New("card_info 中 acc_id 不为空"))
	}
	return service.GetAssetSrv().MemberBalancePay(ctx, req.MemberId, cardInfo.AccId, req)
}

// MemberBalanceRefund 会员余额退款
func (hl *aRpcHandler) MemberBalanceRefund(ctx context.Context, req *pb.MemberBalanceRefundReq) (*pb.BalanceInfoReply, error) {
	if req == nil {
		return nil, nil
	}
	cardInfo := &object.CardInfo{}
	err := json.Unmarshal(req.CardInfo, cardInfo)
	if err != nil {
		return nil, lueerror.InvalidRequest(err)
	}
	if cardInfo.AccId == 0 {
		return nil, lueerror.InvalidRequest(errors.New("card_info 中 acc_id 不为空"))
	}
	return service.GetAssetSrv().MemberBalanceRefund(ctx, req.MemberId, cardInfo.AccId, req)
}
